package com.mmcro.oauth.granter;

import com.mmcro.oauth.Token.ImageCredential;
import com.mmcro.oauth.Token.UImageCodeAuthenticationToken;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义 用户名 + 密码 + 图形验证码
 *
 **/
public class UNameImageCodeTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "uimagecode";

    private final AuthenticationManager authenticationManager;

    public UNameImageCodeTokenGranter(AuthenticationManager authenticationManager,
                                      AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
    }

    private UNameImageCodeTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                       ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        String username = parameters.get("username");
        String password = parameters.get("password");
        String code = parameters.get("code");

        // 验证用户存在 和密码是否正确
        Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
        try {
            userAuth = this.authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException var8) {
            throw new InvalidGrantException(var8.getMessage() + "账户不存在");
        } catch (BadCredentialsException var9) {
            throw new InvalidGrantException(var9.getMessage() + "密码不正确");
        }

        //  验证 code 与redis 当中是否一致
         userAuth = new UImageCodeAuthenticationToken(username,new ImageCredential(password,code));
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            //  这里最终调用的是的对应provider UImageCodeAuthenticationProvider 中的方法
            //  authenticate(Authentication authentication)
            userAuth = authenticationManager.authenticate(userAuth);
        }

        catch (AccountStatusException ase) {
            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
            throw new InvalidGrantException(ase.getMessage());
        }
        catch (BadCredentialsException e) {
            // If the username/password are wrong the spec says we should send 400/invalid grant
            throw new InvalidGrantException(e.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate 密码或图形验证码错误: " + code );
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
